<template>
  <div class="report-preview-page">
    <el-card class="preview-card">
      <div class="preview-header">
        <span class="preview-title">{{ report?.name || '报表预览' }}</span>
        <el-button size="small" @click="goBack">返回</el-button>
      </div>
      <div v-if="!report">
        <el-empty description="未找到对应报表" />
      </div>
      <template v-else>
        <el-descriptions :column="3" style="margin-bottom:16px">
          <el-descriptions-item label="分组">{{ report.group }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ report.created }}</el-descriptions-item>
          <el-descriptions-item label="类型">{{ chartTypeMap[report.chartType] }}</el-descriptions-item>
          <el-descriptions-item label="描述" :span="3">{{ report.desc }}</el-descriptions-item>
        </el-descriptions>
        <div style="margin-bottom:12px;">
          <el-radio-group v-model="chartType" size="small">
            <el-radio-button label="table">表格</el-radio-button>
            <el-radio-button label="bar">柱状图</el-radio-button>
            <el-radio-button label="line">折线图</el-radio-button>
            <el-radio-button label="pie">饼图</el-radio-button>
            <el-radio-button label="funnel">漏斗图</el-radio-button>
          </el-radio-group>
          <el-button size="small" @click="exportExcel" style="margin-left:8px;">导出为Excel</el-button>
          <el-button size="small" @click="exportImg" style="margin-left:8px;">导出为图片</el-button>
        </div>
        <div v-if="chartType === 'table'">
          <el-table :data="report.data" border height="340">
            <el-table-column v-for="f in report.fields" :key="f" :prop="f" :label="f" />
          </el-table>
        </div>
        <div v-else>
          <v-chart :option="getEchartsOption(report, chartType)" autoresize style="height:350px;" ref="chartRef" />
        </div>
      </template>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import * as XLSX from 'xlsx'
import VChart from 'vue-echarts'
import html2canvas from 'html2canvas'

const router = useRouter()
const route = useRoute()
const chartTypeMap = {
  table: '表格',
  bar: '柱状图',
  line: '折线图',
  pie: '饼图',
  funnel: '漏斗图'
}

const report = ref(null)
const chartType = ref('table')
const chartRef = ref()

// 1. 加载报表数据
onMounted(() => {
  const all = JSON.parse(localStorage.getItem('reports') || '[]')
  const current = all.find(r => r.id === Number(route.params.id))
  if (current) {
    report.value = current
    chartType.value = current.chartType || 'table'
  }
})

// 2. 返回到报表列表
function goBack() {
  router.push({ name: 'MultiDimReport' })
}

// 3. 导出为Excel
function exportExcel() {
  if (!report.value) return
  const ws = XLSX.utils.json_to_sheet(report.value.data)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, report.value.name || '报表数据')
  XLSX.writeFile(wb, `${report.value.name || '报表'}.xlsx`)
}

// 4. 导出为图片（如果是图表）
async function exportImg() {
  if (chartType.value === 'table') {
    // 表格截图
    const el = document.querySelector('.el-table')
    if (!el) return
    const canvas = await html2canvas(el, { useCORS: true })
    const link = document.createElement('a')
    link.href = canvas.toDataURL('image/png')
    link.download = (report.value?.name || '报表') + '.png'
    link.click()
  } else {
    // 图表截图
    // 推荐直接用echarts的getDataURL
    const echartInstance = chartRef.value?.getEchartsInstance?.()
    if (echartInstance) {
      const url = echartInstance.getDataURL({ pixelRatio: 2, backgroundColor: '#fff' })
      const link = document.createElement('a')
      link.href = url
      link.download = (report.value?.name || '报表') + '.png'
      link.click()
    }
  }
}

// 5. 生成ECharts配置
function getEchartsOption(row, type) {
  const data = row?.data || []
  if (!data.length) return {}
  // 以“日期”为X轴，“数值”为Y轴
  const xField = row.fields.find(f => ['日期', '类别', '产品', '地区', '客户', '负责人', '渠道'].includes(f)) || row.fields[0]
  const yField = row.fields.find(f => ['数值', '销售额', '数量', '成本', '利润'].includes(f)) || row.fields[1]
  const xData = data.map(d => d[xField])
  const yData = data.map(d => d[yField])
  if (type === 'bar') {
    return {
      tooltip: { trigger: 'axis' },
      xAxis: { type: 'category', data: xData },
      yAxis: { type: 'value' },
      series: [{ name: yField, type: 'bar', data: yData, itemStyle: { borderRadius: 4 } }]
    }
  } else if (type === 'line') {
    return {
      tooltip: { trigger: 'axis' },
      xAxis: { type: 'category', data: xData },
      yAxis: { type: 'value' },
      series: [{ name: yField, type: 'line', data: yData, smooth: true }]
    }
  } else if (type === 'pie') {
    return {
      tooltip: { trigger: 'item' },
      series: [
        {
          name: yField,
          type: 'pie',
          radius: ['40%', '80%'],
          data: data.map(d => ({ value: d[yField], name: d[xField] }))
        }
      ]
    }
  } else if (type === 'funnel') {
    return {
      tooltip: { trigger: 'item' },
      series: [
        {
          name: yField,
          type: 'funnel',
          left: '10%',
          width: '80%',
          minSize: '40%',
          label: { show: true, position: 'inside' },
          data: data.map(d => ({ value: d[yField], name: d[xField] }))
        }
      ]
    }
  }
  return {}
}
</script>

<style scoped>
.report-preview-page {
  padding: 24px;
  background: #f7f8fa;
}
.preview-card {
  max-width: 900px;
  margin: 0 auto;
  border-radius: 12px;
}
.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
.preview-title {
  font-size: 20px;
  font-weight: 600;
}
</style>
